package com.photoeditor.demo.ui.activity.subscribe;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.event.AddVideoTextEveryVideoEvent;
import com.photoeditor.demo.model.event.AgeSuccessEvent;
import com.photoeditor.demo.model.event.FeedBackEvent;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.ui.filter.VideoSubtitleFilter;
import com.photoeditor.demo.ui.widget.SubscribePlayerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import static com.photoeditor.demo.ui.activity.subscribe.SubscribeVideoActivity.getVideoResIds;
import static com.photoeditor.demo.util.DisplayUtils.dp2px;


/**
 * 带有订阅视频的订阅页面
 * Created by zhangwei on 19-6-26.
 */
public abstract class BaseSubscribeVideoActivity extends BaseSubscribeActivity {

    private SubscribePlayerView mPlayerView;
    private ArrayList<long[]> videoStartAndEndPosMsList;
    private int[] videoResIds;
    private int videoResId;
    private long[] posMs;
    private int videoIndex=0;
    private float mRatio = 1f;
    private boolean isFunctionSubscribe;
    protected String entrance;
    private String text;
    protected String entranceStatistic;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent != null) {
            //对应变老，换性等
            entrance = intent.getStringExtra(EXTRA_STATISTICS_ENTRANCE);
            //对应滤镜和贴纸
            entranceStatistic = intent.getStringExtra(EXTRA_STATISTICS_ENTRANCE_STATISTIC);
            isFunctionSubscribe=intent.getBooleanExtra(EXTRA_IS_FUNCTION_SUBSCRIBE,false);
        }

        //这个是为了考虑滤镜和贴纸
        if(entranceStatistic!=null){
            if(entranceStatistic.equals(StatisticsConstant.ENTRANCE_VALUE_FILTER) || entranceStatistic.equals(StatisticsConstant.ENTRANCE_VALUE_STICKER)){
                //滤镜和贴纸不需要设置播放器，因为显示图片，播放器隐藏为空
                return;
            }
        }
        //获取哪一个订阅视频，从而拿到需要显示的字幕
        switch (entrance) {
            case "aging":
                text = getString(R.string.sub_video_facing_aging);
                break;
            case "gender":
                text = getString(R.string.sub_video_gender_swap);
                break;
            case "past":
                text = getString(R.string.sub_video_past_life);
                break;
            case "baby":
                text = getString(R.string.baby_prediction);
                break;
            default:
                text = getString(R.string.sub_video_cartoon_effect);
                break;
        }
        //开始设置播放器
        if (setupPlayerView(isFunctionSubscribe,entrance)) {
            if(isFunctionSubscribe){//功能订阅页采用这种方式添加字幕，因为它是单个视频，很好绘制
                addSubtitle(text,600L,false,false);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFeedBackEvent(AddVideoTextEveryVideoEvent event) {
        //因为滤镜是两行的，所以分开处理，还有滤镜和其他的开始时间也不一样
        addSubtitle(event.text,event.startDelayMs,event.isTowLine,event.isTowLineSecondLine);
        //开始绘制
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mPlayerView != null) {
            mPlayerView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if ( mPlayerView != null) {
            mPlayerView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPlayerView != null) {
            mPlayerView.onDestroy();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (mPlayerView != null) {
            mPlayerView.onWindowFocusChanged(hasFocus);
        }
    }

    //获取视频播放view和背景等
    private boolean setupPlayerView(boolean isFunctionSubscribe,String entrance) {
        mPlayerView = getPlayerView();
        if (mPlayerView == null) {
            return false;
        }
        long[] posMs = getVideoStartAndEndPosMs();
        if (posMs == null || posMs.length != 2) {
            return false;
        }

        long startPosMs = posMs[0];
        long endPosMs = posMs[1];
        if (startPosMs < 0L) {
            startPosMs = 0L;
        }
        if (endPosMs <= startPosMs) {
            return false;
        }

        //设置播放器
        mPlayerView.setup(startPosMs, endPosMs,isFunctionSubscribe,entrance);
        //每个订阅视频对应的第一帧，为了防止视频播放器刚开始黑屏
        if(isFunctionSubscribe){
            switch (entrance) {
                case "aging":
                    mPlayerView.setVideoForegroundView(getVideoForegroundView(R.drawable.aging_first_image));
                    break;
                case "gender":
                    mPlayerView.setVideoForegroundView(getVideoForegroundView(R.drawable.gender_first_image));
                    break;
                case "past":
                    mPlayerView.setVideoForegroundView(getVideoForegroundView(R.drawable.past_first_image));
                    break;
                case "baby":
                    mPlayerView.setVideoForegroundView(getVideoForegroundView(R.drawable.baby_first_image));
                    break;
                default:
                    mPlayerView.setVideoForegroundView(getVideoForegroundView(R.drawable.filter_first_image));
                    break;
            }
        }else{
            //整个视频的第一帧
            mPlayerView.setVideoForegroundView(getVideoForegroundView(R.drawable.filter_first_image));
        }
        //手机屏幕的宽度像素/视频的宽的大小
        mRatio = DeviceUtils.getScreenWidthPx() / (float) getSrcVideoSize()[0];

        return true;
    }

    /**
     * 获取视频播放view
     * @return
     */
    protected abstract SubscribePlayerView getPlayerView();

    //获取源视频--raw
    protected abstract int getVideoResId();

    /**
     * 获取源视频宽高
     * @return 单位：像素。[0]宽；[1]高
     */
    protected abstract int[] getSrcVideoSize();

    /**
     * 获取视频开始和结束位置
     * @return [0]开始位置；[1]结束位置
     */
    protected abstract long[] getVideoStartAndEndPosMs();

    //获取源视频的具体位置，视频所在的矩形位置
    protected abstract Rect getPlayerPosition();

    /**
     * 获取视频播放前遮罩
     * @return
     */
    protected abstract View getVideoForegroundView(int imageId);


    //获取比例
    protected float getRatio() {
        return mRatio;
    }

    /**
     * 在视频上面添加字幕
     * @param
     */
    public void addSubtitle(String text,long startDelayMs,boolean isTwoLine,boolean isTowLineSecondLine) {
        float textSize = getTextSize(37f);
        int textColor = Color.WHITE;
        int margin = 0;
        //text = getString(R.string.sub_video_gender_swap );
        addVideoTextAlphaCenterVideo(text, textSize, textColor, Typeface.DEFAULT_BOLD, margin, margin,startDelayMs,isTwoLine,isTowLineSecondLine);

//        //aging
//        text = getString(R.string.sub_video_facing_aging );
//        addVideoTextAlphaCenterVideo(text, textSize, textColor, Typeface.DEFAULT_BOLD, margin, margin,160L,false,false);
//
//        //past life
//        text = getString(R.string.sub_video_past_life);
//        addVideoTextAlphaCenterVideo(text, textSize, textColor, Typeface.DEFAULT_BOLD, margin, margin,160L,false,false);
//
//        //Beauty&
//        text = getString(R.string.sub_video_beauty);
//        addVideoTextAlphaCenterVideo(text, textSize, textColor, Typeface.DEFAULT_BOLD, margin, margin,160L,true,false);
//
//        //Cartoon Effect
//        text =getString(R.string.sub_video_cartoon_effect);
//        addVideoTextAlphaCenterVideo(text, textSize, textColor, Typeface.DEFAULT_BOLD, margin, margin,160L,true,true);
    }

    public int[] getTextWH(String text, float textSize, Typeface textFont) {
        if (TextUtils.isEmpty(text)) {
            return new int[] {0, 0};
        }

        int[] size = new int[2];

        Paint paint = new Paint();
        paint.setTextSize(textSize);
        paint.setTypeface(textFont);

        int index = text.indexOf("\n");
        if (index < 0) {
            Rect bounds = new Rect();
            paint.getTextBounds(text, 0, text.length(), bounds);
            size[0] = bounds.width();
            size[1] = bounds.height();
        } else {
            int width = 0;
            int height = 0;
            String[] texts = text.split("\n");
            for (String str : texts) {
                Rect bounds = new Rect();
                paint.getTextBounds(str, 0, str.length(), bounds);
                width = width < bounds.width() ? bounds.width() : width;
                height += bounds.height();
            }
            size[0] = width;
            size[1] = height;
        }

        return size;
    }

    /**增加视频中心文字透明度
     * @param text 具体的文字
     * @param textSize 文字大小
     * @param textColor 文字颜色
     * @param textFont 文字字体
     * @param marginLeft
     * @param marginRight
     * @param startDelayMs 视频开始时间
     */
    public void addVideoTextAlphaCenterVideo(String text, float textSize, int textColor, Typeface textFont,
                                              int marginLeft, int marginRight,
                                              long startDelayMs,boolean isTwoLine,boolean isTowLineSecondLine) {
        int x=0;
        int y=0;
        int[] wh;
        if(isTwoLine){
            //有二行
            if(isTowLineSecondLine){
                //第二行
                wh= getTextWH(text, textSize, textFont);
                x= getSubtitleCenterXPos(text, textSize, marginLeft, marginRight, textFont);
                y= getSubtitleCenterYPos(text, textSize, marginLeft, marginRight, textFont)+(wh[1]);

            }else{
                //第一行
                wh= getTextWH(text, textSize, textFont);
                x= getSubtitleCenterXPos(text, textSize, marginLeft, marginRight, textFont);
                y= getSubtitleCenterYPos(text, textSize, marginLeft, marginRight, textFont)-(wh[1]/2);
            }
        }else{
            //只有一行的时候
            x= getSubtitleCenterXPos(text, textSize, marginLeft, marginRight, textFont);
            y= getSubtitleCenterYPos(text, textSize, marginLeft, marginRight, textFont);
        }


        long start = startDelayMs;
        long end = start + 200;
        //位移和透明度变化文字
        mPlayerView.addSubtitleTranslateScaleAlphaAnim(text, textSize, textColor, textFont, start, end, x, x, y, y, 0f, 1f,0.04f,1.02f);

        start = end;
        end = start + 120;
        mPlayerView.addSubtitleTranslateScaleAlphaAnim(text, textSize, textColor, textFont, start, end, x, x, y, y, 1f, 1f,1.02f,0.99f);


        start = end;
        end = start + 160;
        mPlayerView.addSubtitleTranslateScaleAlphaAnim(text, textSize, textColor, textFont, start, end, x, x, y, y, 1f, 1f,0.99f,1.003f);

        start = end;
        end = start + 160;
        mPlayerView.addSubtitleTranslateScaleAlphaAnim(text, textSize, textColor, textFont, start, end, x, x, y, y, 1f, 1f,1.003f,1f);

        start = end;
        end = start + 920;
        mPlayerView.addSubtitle(text, textSize, textColor, textFont, start, end, x, y);


    }

    protected float getTextSize(float sizeOnVideo) {
        return DeviceUtils.sp2pxF(sizeOnVideo) * getRatio();
    }

    protected int getSubtitleXPos(int posXOnVideo) {
        if (mPlayerView == null) {
            return 0;
        }

        Rect pos = getPlayerPosition();
        if (pos == null) {
            return 0;
        }

        return pos.left + (int) (posXOnVideo * mRatio);
    }

    protected int getSubtitleYPos(int posYOnVideo) {
        if (mPlayerView == null) {
            return 0;
        }

        Rect pos = getPlayerPosition();
        if (pos == null) {
            return 0;
        }

        return pos.top + (int) (posYOnVideo * mRatio);
    }

    protected int getSubtitleCenterXPos(String text, float textSize, int marginLeft, int marginRight, Typeface textFont) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        }

        Rect pos = getPlayerPosition();
        if (pos == null) {
            return 0;
        }
        int playerWidth = pos.right - pos.left;

        int[] wh = getTextWH(text, textSize, textFont);
        int textWidth = wh[0];

        /*Rect bounds = new Rect();
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
        int textWidth = bounds.right - bounds.left;*/

        if (textWidth + marginLeft + marginRight >= playerWidth) {
            return marginLeft;
        } else {
            return (playerWidth - textWidth - marginLeft - marginRight) / 2 + marginLeft;
        }
    }

    protected int getSubtitleCenterYPos(String text, float textSize, int marginTop, int marginBottom, Typeface textFont) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        }

        Rect pos = getPlayerPosition();
        if (pos == null) {
            return 0;
        }
        int playerHeight = pos.bottom - pos.top;

        Rect bounds = new Rect();
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
        //int textHeight = bounds.bottom - bounds.top;
        int[] wh = getTextWH(text, textSize, textFont);
        int textHeight = wh[1];
        if (textHeight + marginTop + marginBottom >= playerHeight) {
            return marginTop;
        } else {
            return (playerHeight - textHeight - marginTop - marginBottom) / 2 + marginTop;
        }
    }
}
